package com.info33.platform.business.dialogue.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.info33.platform.business.dialogue.dao.AiSessionRecordDao;
import com.info33.platform.business.dialogue.dto.AiSessionRecordDTO;
import com.info33.platform.business.dialogue.entity.AiConversation;
import com.info33.platform.business.dialogue.entity.AiSessionRecord;
import com.info33.platform.business.dialogue.service.AiConversationService;
import com.info33.platform.business.dialogue.service.AiSessionRecordService;
import com.info33.platform.common.mvc.vo.Result;
import com.info33.platform.common.util.OKHttpUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.net.BindException;
import java.util.*;

/**
 * @author LF
 * @date 2023-10-16 10:09:15
 */
@Service
public class AiSessionRecordServiceImpl extends ServiceImpl<AiSessionRecordDao, AiSessionRecord> implements AiSessionRecordService {

    @Autowired
    private AiSessionRecordDao aiSessionRecordDao;
    @Autowired
    private AiConversationService aiConversationService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> askQuestion(AiSessionRecordDTO dto) throws IOException {
        String token = "24.8214f68a6e21355de96cab6b276d6a8c.2592000.1699609944.282335-40879528";
        // ERNIE-Bot
//        String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions";
        // ERNIE-Bot-turbo
        String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant";
        String allUrl = url + "?access_token=" + token;
        JSONObject params = new JSONObject();

        int sort = 1;
        // 查询是否存在历史提问记录
        List<AiSessionRecord> recordList = list(new QueryWrapper<AiSessionRecord>().eq("conversation_id", dto.getConversationId()).orderByAsc("sort"));
        List<Map> list = new ArrayList<>();
        if (recordList.size() > 0) {
            for (AiSessionRecord record : recordList) {
                Map<String, String> map = new HashMap<>(2);
                map.put("role", record.getRole());
                map.put("content", record.getContent());
                list.add(map);
                if (record.getSort() > sort) {
                    sort = record.getSort();
                }
            }
            sort += 1;
        }

        Map<String, String> map = new HashMap<>(2);
        map.put("role", "user");
        map.put("content", dto.getContent());
        list.add(map);

        AiSessionRecord problem = new AiSessionRecord();
        BeanUtils.copyProperties(dto, problem);
        problem.setRole("user");

        problem.setSort(sort);
        String content = null;
        Long conversationId = problem.getConversationId();
        if (save(problem)) {
            params.put("messages", list);
            System.out.println(list);
            Map<String, Object> dopost = OKHttpUtil.dopost(allUrl, params);
            if ("200".equals(dopost.get("status").toString())) {
                JSONObject infoJSON = JSON.parseObject(dopost.get("result").toString());
                content = infoJSON.get("result").toString();
            }
        }

        if (StringUtils.isNotBlank(content)) {
            AiSessionRecord reply = new AiSessionRecord();
            reply.setConversationId(conversationId);
            reply.setRole("assistant");
            reply.setContent(content);
            reply.setSort(problem.getSort() + 1);
            if (save(reply)) {
                AiConversation conversation = aiConversationService.getById(conversationId);
                conversation.setLastQuestionTime(new Date());
                if (aiConversationService.updateById(conversation)) {
                    return Result.ok(content);
                }
            }
        }
        throw new BindException("增加记录失败!");
    }

    @Override
    public List<JSONObject> recordList() {
        List<JSONObject> list = new ArrayList<>();
        List<AiSessionRecord> recordList = list(new QueryWrapper<AiSessionRecord>().eq("status", 1).orderByAsc("sort"));
        recordList.forEach(x->{
            String name = "";
            if ("user".equals(x.getRole())) {
                name = "用户提问： ";
            }
            if ("assistant".equals(x.getRole())){
                name = "智能AI： ";
            }
            JSONObject object = new JSONObject();
            object.put("text",name+x.getContent());
            list.add(object);
        });
        return list;
    }

    @Override
    public Result<?> updateTest(AiSessionRecordDTO dto) {

        List<Object> ids = Arrays.asList("1","2","3","4");
        AiSessionRecord aiSessionRecord = new AiSessionRecord();
        aiSessionRecord.setRole("可以");
        int id = aiSessionRecordDao.update(aiSessionRecord, new QueryWrapper<AiSessionRecord>().in("id", ids));
        System.out.println(id);
//        boolean update = update(aiSessionRecord, new QueryWrapper<AiSessionRecord>().in("id", ids));
//        System.out.println(update);



        return null;
    }

    @Override
    public Result<?> streamingQuery() {
        QueryWrapper<AiSessionRecord> queryWrapper = new QueryWrapper<>();
        List<AiSessionRecord> list = new ArrayList<>();
        return Result.ok(list);
    }
}
